<template>
  <div class="app-container">
    <h1>药品详情</h1>
    <el-table v-loading="isDrugListLoading" :data="drugList">
      <el-table-column prop="name" label="药品" />
      <el-table-column prop="cnt" label="次数" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleDrugDetails(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <h1>医院详情</h1>
    <el-table v-loading="isHospitalListLoading" :data="hospitalList">
      <el-table-column prop="name" label="医院" />
      <el-table-column prop="cnt" label="次数" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleHospitalDetails(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <h1>购买详情</h1>
    <el-select v-model="selectedColumns" multiple searchable placeholder="选择显示列" style="width: 50%" size="medium">
      <el-option
        v-for="item in tableColumns"
        :key="item.prop"
        :label="item.label"
        :value="item.prop"
      />
    </el-select>
    <el-table v-loading="isPurchaseSummaryLoading" :data="purchaseSummary">
      <el-table-column v-if="selectedColumns.includes('hospital')" align="center" min-width="180px">
        <!-- header slot-->
        <template v-slot:header>
          <el-select
            v-model="formData.hospital"
            filterable
            clearable
            placeholder="医院"
            size="small"
            multiple
            @visible-change="summarizePurchaseHistory()"
          >
            <el-option
              v-for="item in hospitalDDList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
        <!-- 表格数据 value slot -->
        <template slot-scope="scope">
          {{ scope.row.hospital }}
        </template>
      </el-table-column>

      <el-table-column v-if="selectedColumns.includes('drugName')" align="center" min-width="180px">
        <template v-slot:header>
          <el-select
            v-model="formData.drugName"
            filterable
            clearable
            placeholder="药品名称"
            size="small"
            multiple
            @visible-change="summarizePurchaseHistory()"
          >
            <el-option
              v-for="item in drugNameDDList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
        <template slot-scope="scope">
          {{ scope.row.drugName }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="column in filteredColumns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :min-width="column.minWidth!==''?column.minWidth:''"
        align="center"
      />

    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 25, 50, 100]"
      :total="total"
      hide-on-single-page
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog :visible.sync="dialogVisible" width="50%">
      <el-table v-loading="dialogTableLoading" :data="dialogData" empty-text=" ">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="cnt" label="次数" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import * as summarizeAPI from '@/api/summarize'

export default {
  data() {
    return {
      drugList: [],
      hospitalList: [],
      formData: {},
      idNumber: '',
      dialogVisible: false,
      dialogData: [],
      // 购买详情
      purchaseSummary: [],
      // 表格所有的列
      tableColumns: [
        // { prop: 'treatmentType', label: '治疗类型' },
        // { prop: 'prescriber', label: '开药医生' },
        { prop: 'hospital', label: '医院' },
        { prop: 'drugName', label: '药品名称' },
        { prop: 'patientName', label: '患者姓名', minWidth: '100px' },
        { prop: 'prescriptionTime', label: '处方时间', minWidth: '180px' },
        { prop: 'prescriptionTimeString', label: '原始处方时间', minWidth: '180px' },
        { prop: 'idNumber', label: '身份证号', minWidth: '180px' },
        { prop: 'age', label: '年龄' },
        { prop: 'telephoneNumber', label: '电话号码', minWidth: '130px' },
        { prop: 'specification', label: '规格' },
        { prop: 'quantity', label: '数量' },
        { prop: 'dose', label: '剂量' },
        { prop: 'measurementUnit', label: '计量单位' },
        { prop: 'drugClassification', label: '药品分类' }
      ],
      // 表格显示的列
      selectedColumns: [
        // 'treatmentType',
        // 'prescriber',
        'hospital',
        'drugName',
        'patientName',
        'prescriptionTime',
        'prescriptionTimeString',
        'idNumber',
        'age',
        'telephoneNumber',
        'specification',
        'quantity',
        'dose',
        'measurementUnit',
        'drugClassification'
      ],
      // 分页参数
      page: 1,
      size: 10,
      total: 0,
      // 表格加载
      isDrugListLoading: false,
      isHospitalListLoading: false,
      isPurchaseSummaryLoading: false,
      // 对话框的表格加载
      dialogTableLoading: false
      // 下拉框数据源
      // drugNameDDList: [],
      // hospitalDDList: []
    }
  },
  computed: {
    filteredColumns() {
      // 根据 selectedColumns 过滤 tableColumns，只显示 selectedColumns 中包含的列
      return this.tableColumns.filter(column => this.selectedColumns.includes(column.prop))
    },
    drugNameDDList() {
      return this.drugList.map(item => item.name)
    },
    hospitalDDList() {
      return this.hospitalList.map(item => item.name)
    }
  },
  created() {
    // 判断是否能取得参数
    if (!this.$route.params.idNumber) {
      this.$message({
        message: '数据为空，请不要在本页面刷新。3 秒后自动返回上一页',
        type: 'warning',
        duration: 3000
      })
      setTimeout(() => {
        this.$router.go(-1)
      }, 3000)
      // 退出执行
      return
    } else {
      this.idNumber = this.$route.params.idNumber
    }

    // 获取路由参数
    this.formData = this.$route.params.formData
    this.idNumber = this.$route.params.idNumber
    // 汇总数据
    this.summarizeDrugList()
    this.summarizeHospitalList()
    this.summarizePurchaseHistory()
  },
  methods: {
    summarizeDrugList() {
      this.isDrugListLoading = true
      const idNumber = this.idNumber
      const formData = this.formData
      summarizeAPI.summarizeByDrugName({ idNumber }, formData)
        .then(response => {
          this.drugList = response.data.list
          this.formData.drugName = this.drugNameDDList
          this.isDrugListLoading = false
        })
        .catch(error => {
          console.error(error)
          this.isDrugListLoading = false
        })
    },
    summarizeHospitalList() {
      this.isHospitalListLoading = true
      const idNumber = this.idNumber
      const formData = this.formData
      summarizeAPI.summarizeByHospital({ idNumber }, formData)
        .then(response => {
          this.hospitalList = response.data.list
          this.formData.hospital = this.hospitalDDList
          this.isHospitalListLoading = false
        })
        .catch(error => {
          console.error(error)
          this.isHospitalListLoading = false
        })
    },
    summarizePurchaseHistory() {
      this.isPurchaseSummaryLoading = true
      const idNumber = this.idNumber
      const formData = this.formData
      const page = this.page
      const size = this.size
      summarizeAPI.summarizeByPurchase({ idNumber, page, size }, formData)
        .then(response => {
          this.purchaseSummary = response.data.list
          this.total = response.data.total // 更新总数
          this.isPurchaseSummaryLoading = false
        })
        .catch(error => {
          console.error(error)
          this.isPurchaseSummaryLoading = false
        })
    },
    fetchDrugDetails(idNumber, drugName) {
      this.dialogTableLoading = true
      this.dialogVisible = true
      const { prescriptionStartTime, prescriptionEndTime } = this.formData
      summarizeAPI.summarizeDrug({ idNumber }, { prescriptionStartTime, prescriptionEndTime, drugName })
        .then(response => {
          this.dialogData = response.data.list
          this.dialogTableLoading = false
        })
        .catch(error => {
          console.error(error)
          this.dialogTableLoading = false
        })
    },
    fetchHospitalDetails(idNumber, hospitalName) {
      this.dialogTableLoading = true
      this.dialogVisible = true
      const { prescriptionStartTime, prescriptionEndTime } = this.formData
      summarizeAPI.summarizeHospital({ idNumber }, { prescriptionStartTime, prescriptionEndTime, hospitalName })
        .then(response => {
          this.dialogData = response.data.list
          this.dialogTableLoading = false
        })
        .catch(error => {
          console.error(error)
          this.dialogTableLoading = false
        })
    },
    handleDrugDetails(row) {
      this.dialogData = []
      this.fetchDrugDetails(this.idNumber, row.name)
    },
    handleHospitalDetails(row) {
      this.dialogData = []
      this.fetchHospitalDetails(this.idNumber, row.name)
    },
    // 过滤器处理函数
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    // 分页：每页显示数量改变
    handleSizeChange(val) {
      this.size = val
      this.summarizePurchaseHistory()
    },
    // 分页：页码改变
    handleCurrentChange(val) {
      this.page = val
      this.summarizePurchaseHistory()
    },
    handlerOptionsBlur() {
      console.log('asdasd')
    }
    // 获取下拉菜单的数据 废弃，下一版本删除
    // fetchDropdownData() {
    //   // 获取药品名称列表
    //   commonApi.getDrugNameList()
    //     .then(response => {
    //       if (response.code === 200) {
    //         this.drugNameDDList = response.data.list
    //       } else {
    //         console.error(response.msg)
    //       }
    //     })
    //     .catch(error => {
    //       console.error(error)
    //     })
    //
    //   // 获取医院列表
    //   commonApi.getHospitalList()
    //     .then(response => {
    //       if (response.code === 200) {
    //         this.hospitalDDList = response.data.list
    //       } else {
    //         console.error(response.msg)
    //       }
    //     })
    //     .catch(error => {
    //       console.error(error)
    //     })
    // }
  }
}
</script>
